package com.lwt.codetop.arrayOrSort;

// 手撕快速排序
public class QuickSort {
    private static int[] nums;
    public static void main(String[] args) {
        // 构建测试用例
        nums = new int[]{5, 3, 2, 4, 1};
        int n = nums.length;
        // 快排
        quick_sort(nums, 0, n - 1);
        for (int x : nums) {
            System.out.print(x + " ");
        }

    }

    /**
     * 递归实现快速排序：分化左右两边 左边小于x x 右边大于x; 递归排序左右两边
     * @param nums
     */
    private static void quick_sort(int[] nums, int l, int r) {
        if(l >= r) return;
        int x = nums[l + r >> 1];
        int i = l - 1, j = r + 1;
        while(i < j){
            do i ++; while(nums[i] < x);
            do j --; while (nums[j] > x);
            if(i < j){
                int tmp = nums[i];
                nums[i] = nums[j];
                nums[j] = tmp;
            }
        }
        quick_sort(nums, l, j);
        quick_sort(nums, j + 1, r);
    }
}
